import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute, Router } from '@angular/router';
import { DatePipe } from '@angular/common';
import { NzModalService } from 'ng-zorro-antd/modal';

import { BehaviorSubject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

import { CommonService } from 'src/app/services-common/common.service';
import { LoveOrderManageService } from '../love-order-manage.service';
import { LoveRecycManageService } from '../love-recyc-manage.service';
import { orderStateArrs, machineResultArrs, machineInspectionArrs } from '../love-recyc-manage.pipe';

@Component({
  selector: 'app-love-order-manage',
  templateUrl: './love-order-manage.component.html',
  styleUrls: ['./love-order-manage.component.scss'],
  providers: [DatePipe]
})
export class LoveOrderManageComponent implements OnInit, OnDestroy {
  @ViewChild('expnoRef') expnoRef: any;
  @ViewChild('userInfoRef') userInfoRef: any;

  // 路由缓存恢复时
  static updateCache: any = null;
  isCollapse: boolean = true;

  seachParams: any = {
    okey: '', // 订单号
    expno: '', // 快递单号
    renewalNo: '', // 靓机单号
    phoneCode: '', // 机器编号
    phoneSerialNumber: '', // 机器序列号
    umname: '', // 机型
    lnker: '', // 寄件人
    orderType: '', // 下单身份
    userId: '', // 用户身份
    restype: '', // 验机结果
    checkStatus: '', // 验机状态
    backI5addrid: '', // 退货信息 0: 无、1: 有
    orderWay: '', // 下单方式
    category: '', // 下单方式
    cidList: [], // 推广渠道
    otime11BeginTime: '', // 下单开始时间
    otime11EndTime: '', // 下单结束时间
    otime13BeginTime: '', // 揽件开始时间
    otime13EndTime: '', // 揽件结束时间
    otime14BeginTime: '', // 到货签收开始时间
    otime14EndTime: '', // 到货签收结束时间
    otime19BeginTime: '', // 成交开始时间
    otime19EndTime: '', // 成交结束时间
  };
  // 订单来源optiuons
  orderSourceOptions: any = [];
  orderSourceSelected: any = [];
  // 验机状态
  machineStateOptions: any = [...machineInspectionArrs];
  // 订单状态options
  orderStateOptions: any = [...orderStateArrs];
  orderStateSelected: any = [];
  // 验机结果
  resultOptions: any = [...machineResultArrs]
  // 下单时间
  placeOrderTimes: any = [];
  // 揽件时间
  solicitationTimes: any = [];
  // 到货签收时间
  signForTimes: any = [];
  // 成交时间
  dealTimes: any = [];
  // 品牌options
  brandOptions: any = [];

  // 验机结果Array Selected
  restypeSelected: any = [];
  // 验机状态Array Selected
  checkStatusSelected: any = [];
  // 品牌Array Selected
  brandSelected: any = [];

  tableData: any = [];
  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  }

  // 用户信息
  modalUserId: any = null;

  // 跟进 Modal
  followUpForm!: FormGroup;
  isFollowVisible: boolean = false;
  singleItems: any = {};

  // 导出 Export
  exportLoading: boolean = false;

  // 推广渠道list
  extensionOptions: any = [];

  // 机器编码防抖
  searchCodeChange$ = new BehaviorSubject('');

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private datePipe: DatePipe,
    private modal: NzModalService,
    private commonService: CommonService,
    private message: NzMessageService,
    private services: LoveOrderManageService,
    private loveRecycManageService: LoveRecycManageService,
    public activatedRoute: ActivatedRoute,
  ) { }

  ngOnInit() {
    if (this.activatedRoute.snapshot.queryParams.logisticsCode) {
      this.seachParams.expno = this.activatedRoute.snapshot.queryParams.logisticsCode;
    }
    if (this.activatedRoute.snapshot.queryParams.okey) {
      this.seachParams.okey = this.activatedRoute.snapshot.queryParams.okey;
    }
    this.followUpForm = this.fb.group({
      remarks: ['', [Validators.required]],
    });

    LoveOrderManageComponent.updateCache = () => {
      this.getChannelList();
      this.queryExtension();
      this.loadBrandListData();
      this.loadTable();
    };

    this.getChannelList();
    this.queryExtension();
    this.loadBrandListData();
    this.loadTable();

    // 机器编码输入防抖(扫码枪)
    this.searchCodeChange$
      .pipe(debounceTime(500))
      .subscribe(data => {
        if (data.includes('i5.cn')) {
          let startIndex = data.lastIndexOf('/');
          let scanStr = data.substring(startIndex + 1);

          this.seachParams.phoneCode = scanStr;
          this.tableParams.page = 1;
          this.loadTable();
        }
      });
  }

  ngOnDestroy() {
    this.searchCodeChange$.unsubscribe();
  }

  // 查询品牌Options
  async loadBrandListData() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.loveRecycManageService.getRecycleBrandList(params);
    if (code === 0) {
      this.brandOptions = data.records || [];
    }
  }

  // 查询 推广渠道cid
  async queryExtension() {
    this.extensionOptions = await this.commonService.getDictList('iDiy_extension_channel');
  }

  // 查询订单来源
  async getChannelList() {
    const res: any = await this.services.dictListData('channel');
    if (res.code == 0) {
      const { list } = res.data || {};
      this.orderSourceOptions = list || [];
    } else {
      this.message.error(res.message);
    }
  }

  async loadTable() {
    try {
      let params = {
        ...this.seachParams,
        platform: this.orderSourceSelected.join(','), // 订单来源
        ostat: this.orderStateSelected.join(','), // 订单状态
        brandList: this.brandSelected.join(','), // 品牌
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      }
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getOrderList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        const { list, total } = res.data || {};
        this.tableData = list || [];
        this.tableParams.total = total || 0;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.tableParams.tableLoading = false;
      this.message.error(error);
    }
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }
  resetData() {
    for (let key in this.seachParams) {
      if (Array.isArray(this.seachParams[key])) {
        this.seachParams[key] = [];
      } else {
        this.seachParams[key] = '';
      }
    }
    this.orderSourceSelected = []; // 订单来源
    this.orderStateSelected = []; // 订单状态
    this.placeOrderTimes = []; // 下单时间
    this.solicitationTimes = []; // 揽件时间
    this.signForTimes = []; // 到货签收时间
    this.dealTimes = []; // 成交时间
    this.brandSelected = []; // 品牌所选

    this.tableParams.page = 1;
    this.loadTable();
  }

  /**
   * search time change
   * @param result
   * @param keys
   */
  timeChange(result: any, keys: Array<string>) {
    this.seachParams[keys[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.seachParams[keys[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  // 爱思用户信息 Modal
  userInfoPreview(item: any) {
    this.modalUserId = item.user_id;
    this.userInfoRef.isVisible = true;
  }

  // 跟进订单
  openFollowModal(item: any) {
    this.singleItems = item;
    this.followUpForm.reset();
    this.isFollowVisible = true;
  }
  handleCancel() {
    this.isFollowVisible = false;
  }
  submitForm() {
    if (this.followUpForm.valid) {
      this.subFormInterface();
    } else {
      Object.values(this.followUpForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  async subFormInterface() {
    let params = {
      ...this.followUpForm.value,
      id: this.singleItems.id
    }
    const res: any = await this.services.orderFollowUpData(params);
    if (res.code == 0) {
      this.message.success('操作成功');
      this.isFollowVisible = false;
    } else {
      this.message.error(res.message);
    }
  }

  // Export Table
  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ...this.seachParams,
          platform: this.orderSourceSelected.join(','), // 订单来源
          ostat: this.orderStateSelected.join(','), // 订单状态
          brandList: this.brandSelected.join(','), // 品牌
          page: 1,
          pageSize: 999999
        }
        for (let key in params) {
          if (params[key] === null) {
            params[key] = '';
          }

          if (Array.isArray(params[key])) {
            params[key] = params[key].length ? params[key].join(',') : '';
          }
        }
        this.exportLoading = true;
        const res: any = await this.services.recoveryOrderExportData(params);
        this.exportLoading = false;
    
        if (res.type && res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '爱思回收订单');
        } else {
          this.message.error(res.message || '导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 订单来源filter
  filterPlatform(platform: number) {
    let tempObj = this.orderSourceOptions.find((item: any) => {
      return item.content == platform;
    })
    return tempObj ? tempObj.name : '-'
  }

  // search mutiple
  multipleChange(val: any, key: string) {
    this.seachParams[key] = val?.length ? val.join(',') : '';
  }

  // 机器编码Change
  searchCodeChange(val: any) {
    this.searchCodeChange$.next(val);
  }
}
